<template>
  <div class="mv-outer">
    <!-- 搜索版块 -->
    <div class="search_box">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="MV名">
          <el-input placeholder="请输入MV名~" v-model="searchInfo" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button
            type="primary"
            @click="
              () => {
                searchInfo = '';
                getInitData();
              }
            "
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="list_box_but1">
      <el-button type="primary" @click="editRow(1, null)">新增MV</el-button>
    </div>

    <div class="list_box1">
      <div class="list_table">
        <el-table
          size="small"
          :data="data"
          :height="tableHeight"
          stripe
          :header-cell-style="{ background: '#EEF1F6' }"
        >
          <el-table-column
            label="ID"
            prop="mvId"
            width="50"
            align="center"
          ></el-table-column>

          <el-table-column
            label="MV标题"
            prop="name"
            width="120"
            align="center"
          ></el-table-column>
          <el-table-column
            label="歌手"
            prop="author"
            width="120"
            align="center"
          ></el-table-column>
          <el-table-column
            label="MV封面"
            prop="cover"
            width="200"
            align="center"
          >
            <template v-slot="scope">
              <div class="singer-img" v-if="scope.row.cover">
                <img
                  :src="getUrl(scope.row.cover)"
                  style="height: 100px; object-fit: contain"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="MV视频" prop="video" align="center">
            <template v-slot="scope">
              <div class="singer-img" v-if="scope.row.video">
                <video
                  :src="getUrl(scope.row.video)"
                  controls
                  style="height: 100px"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template v-slot="scope">
              <el-button @click="editRow(2, scope.row)">编辑</el-button>
              <el-popconfirm
                title="删除不可恢复，是否确定删除?"
                @confirm="deleteRow(scope.row.mvId)"
              >
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="list_pagination">
      <el-pagination
        class="pagination"
        background
        layout="total, prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogFormVisible" :title="title" width="500">
      <el-form
        ref="formRef"
        :model="mvForm"
        label-position="top"
        :hide-required-asterisk="true"
      >
        <el-form-item
          prop="singId"
          label="歌手"
          :rules="{
            required: true,
            message: '请选择歌手',
            trigger: 'change',
          }"
        >
          <el-select
            v-model="mvForm.singId"
            placeholder="请选择歌手"
            size="large"
            style="width: 240px"
          >
            <el-option
              v-for="item in singerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="MV标题"
          prop="name"
          :rules="{
            required: true,
            message: '请输入MV标题',
            trigger: 'blur',
          }"
        >
          <el-input v-model="mvForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="MV封面">
          <el-upload
            class="avatar-uploader"
            ref="uploadRef"
            :action="getUrl('/mv/upload')"
            :auto-upload="true"
            :data="{ type: 'mvCover' }"
            :show-file-list="false"
            :on-success="coverSuccess"
          >
            <img
              v-if="mvForm.cover"
              :src="getUrl(mvForm.cover)"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="MV视频">
          <el-upload
            class="avatar-uploader"
            ref="uploadRef"
            :action="getUrl('/mv/upload')"
            :auto-upload="true"
            :data="{ type: 'mvVideo' }"
            :show-file-list="false"
            :on-success="videoSuccess"
            :destroy-on-close="true"
          >
            <video
              v-if="mvForm.video"
              :src="getUrl(mvForm.video)"
              class="video"
              controls
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { getMvs, delMv, addMv, updateMv, getAllSinger } from "@/api";
import { getUrl } from "@/utils copy/format";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";

const formRef = ref<FormInstance>();

const data = ref([]);
const tableHeight = ref(0);
const searchInfo = ref("");
tableHeight.value = window.innerHeight - 205;

// 弹窗标题
const title = ref("");
// 添加修改弹窗
const dialogFormVisible = ref(false);
// 表单
const mvForm = reactive({
  mvId: null,
  name: "",
  cover: "",
  name: "",
  author: "",
  video: "",
  singId: "",
});
let singerList = [];
function getAuthor(id: number) {
  const list = singerList.filter((item) => item.id == id);
  return list[0].name;
}
getSinger();
async function getSinger() {
  singerList = await getAllSinger("");
}
// 封面上传成功回调
const coverSuccess = (response: any) => {
  mvForm.cover = response.data;
};
// 视频上传成功回调
const videoSuccess = (response: any) => {
  mvForm.video = response.data;
};
// 表格数据
const tableData = reactive([]); // 记录歌曲，用于显示
const currentPage = ref(1);
const pageSize = ref(10);
const handleCurrentChange = (val: any) => {
  currentPage.value = val;
  console.log(`current page: ${val}`);
  getData();
};
async function handleSearch() {
  currentPage.value = 1;
  tableData.value = data.value = await getMvs(searchInfo.value.trim());
}
function getData() {
  searchInfo.value = "";
  data.value = tableData.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
}

// 获取 MV 数据
getInitData();
async function getInitData() {
  currentPage.value = 1;
  tableData.length = 0;
  const query = "";
  const data = await getMvs(query);
  Object.assign(tableData, data);
  getData();
}

// 编辑MV  新增MV
function editRow(type: number, row: any) {
  if (type == 1) {
    title.value = "添加MV";
    Object.assign(mvForm, {
      name: "",
      cover: "",
      name: "",
      author: "",
      video: "",
    });
  } else {
    title.value = "修改MV";
    Object.assign(mvForm, row);
  }
  dialogFormVisible.value = true;
}

// 提交
async function submitForm(formEl: any) {
  if (!formEl) return;
  formEl.validate(async (valid: any) => {
    if (valid) {
      if (mvForm.mvId) {
        await updateMv({ ...mvForm, author: getAuthor(mvForm.singId) });
      } else {
        await addMv({ ...mvForm, author: getAuthor(mvForm.singId) });
      }
      getInitData();
      dialogFormVisible.value = false;
    } else {
      console.log("error submit!");
      return false;
    }
  });
}

// 删除MV
async function deleteRow(id: number) {
  const res = await delMv(id);
  getInitData();
}
</script>
<style lang="scss" scoped>
@import "@/static/css/common.scss";

svg {
  width: 14px;
  height: 14px;
  fill: #fff;
  margin-right: 4px;
}

:deep(.el-table__cell) {
  border-bottom: none !important;
}

.inner_icon {
  fill: #4d70ff;
  margin-right: 2px;
}

.inner_icon:hover {
  fill: #2d56fa;
}

.mv-outer {
  padding-bottom: 10px;
}

.list_box1 {
  text-indent: 0;
  background: #fff;
  border-radius: 4px;
  overflow: auto;
}
.list_box_but,
.list_table {
  width: 98%;
  margin: 0 auto;
  margin-top: 10px;
}
.list_box_but1 {
  position: absolute;
  top: 18px;
  right: 30px;
}
.list_box_but a {
  color: #fff;
}
.list_pagination {
  //padding-top: 14px;
  text-indent: 0;
  > div {
    justify-content: flex-end;
    margin-right: 20px;
  }
}
.singer-img {
  img {
    object-fit: cover;
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .video {
  width: 300px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
